/*
 * @Description: 
 * @Author: Junhuang
 * @Date: 2022-02-21 23:19:42
 * @LastEditTime: 2022-03-07 16:22:33
 * @LastEditors: Junhuang
 * @Reference: 
 */
'use strict';

const await = require('await-stream-ready/lib/await');

const Controller = require('egg').Controller;

class CommentController extends Controller {
  async save() {
    const { ctx, app } = this;
    let user_id = ctx.authUser.id;

    ctx.validate({
      content: { type: 'string', required: true, desc: '评论内容' },
      video_id: { type: 'int', required: true, desc: '作品id' },
      reply_id: { type: 'int', required: true, desc: '回复评论id' }
    })

    let { content, video_id, reply_id, reply_user_id } = ctx.request.body;

    let user = await app.model.User.findByPk(user_id);
    if (!user) {
      return ctx.apiFail('回复用户id参数错误');
    }

    let video = await app.model.Video.findByPk(video_id);
    if (!video) {
      return ctx.apiFail('视频不存在');
    }

    // 如果是回复评论
    if (reply_id > 0) {
      let rcomment = await app.model.Comment.findByPk(reply_id);
      if (!rcomment) {
        return ctx.apiFail('回复评论id参数错误');
      }
    }

    let res = await app.model.Comment.create({
      content,
      video_id,
      reply_id,
      user_id
    })

    ctx.apiSuccesss(res);
  }

  // 获取某作品的评论列表
  // 路由：/video_comment/:video_id (此处的id是作品的id)
  async comment() {
    const { ctx, app } = this;
    ctx.validate({
      video_id: { type: 'int', required: true, desc: '作品id' },
    });
    let video_id = ctx.params.video_id;
    let res = await app.model.Comment.findAll({
      where: {
        video_id,
        reply_id: 0
      },
      include: [{
        model: app.model.User,
        as: 'send_user',
        attributes: ['id', 'username', 'nickname', 'avatar']
      }, {
        model: app.model.Comment,
        // 【特别注意】此处在关联commnets中，继续进行关联user表
        include: [{
          model: app.model.User,
          as: 'send_user',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }],
      }],
      //【特别注意】注意此处对关联加载项的排序的写法
      order: [['id', 'DESC'], [{ model: app.model.Comment }, 'id', 'ASC']],
    })
    return ctx.apiSuccesss(res);
  }
}

module.exports = CommentController;
